TplData = {}

local cache = {}
local loaded = {}
local checkArr = {}
local dulplicatedArr = {}

local function readTplData(tableName, conTb)
	local condition = ""
	if type(conTb) == "table" and next(conTb) then
		local conStrTb = {}
		for k, v in pairs(conTb) do
			table.insert(conStrTb, tostring(k) .. "='" .. tostring(v) .. "'")
		end
		condition = table.concat(conStrTb, " AND ")
	end

	return C_readTplData(tableName, condition)
end

local function loadTable(t)
	loaded[t] = true
	if cache[t] == nil then
		cache[t] = {}
	end

	local data = readTplData(t, nil)
	if data then
		for _, v in pairs(data) do
			if not cache[t][v.id] then
                cache[t][v.id] = v--TableUtil.readOnly(v)
			end
		end
	end
end

function TplData.getRecord(t, id)
    local sid = tostring(id)
	if id == nil then
		return nil
	end
	if sid == "0" then
		return nil
	end

	if cache[t] == nil then
		cache[t] = {}
	end
	if cache[t][sid] then
		return cache[t][sid]
	end

	if checkArr[t] == nil then
		checkArr[t] = {}
	end

	if checkArr[t][sid] == true then
		dulplicatedArr[t..sid] = true
		return nil
	end


    local data = readTplData(t, {id=sid})
 	checkArr[t][sid] = true

    if data then
        local readOnlyData = data[sid]--TableUtil.readOnly(data[sid])
        cache[t][sid] = readOnlyData
        return readOnlyData
	end

	return nil
end

function TplData.getRecords(t, obj)
	for k1, v1 in pairs(obj) do
		if v1 ~= nil then
			obj[k1] = tostring(v1)
		end
	end

	if not loaded[t] then
		loadTable(t)
	end

	local res = {}
	for k,v in pairs(cache[t]) do
		local flag = true
		for k2, v2 in pairs(obj) do
			if tostring(v[tostring(k2)]) ~= tostring(v2) then
				flag = false
				break
			end
		end

		if flag then
			table.insert(res,v)
		end
	end

	return res
end

function TplData.getRecordsByFunc(t, func, param)
	if func == nil then
		return
	end

	if not loaded[t] then
		loadTable(t)
	end

	local tpl = cache[t]
	local res = {}
	for k,v in pairs(tpl) do
		if func(v, param) then
			table.insert(res, v)
		end
	end

	return res
end

function TplData.isNull(v)
	return tostring(v) == "0" or tostring(v) == "" or v == nil
end

function TplData.isValid(v)
	return not TplData.isNull(v)
end
